<template>
  <div class="study-room">
    <!-- 顶部工具栏 -->
    <div class="study-toolbar">
      <div class="toolbar-left">
        <el-button @click="goBack" circle>
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <div class="course-info">
          <span class="course-title">{{ currentCourse?.title }}</span>
          <span class="lesson-title">{{ currentLesson?.title }}</span>
        </div>
      </div>
      
      <div class="toolbar-center">
        <div class="progress-info">
          <span>{{ currentLessonIndex + 1 }} / {{ totalLessons }}</span>
          <el-progress 
            :percentage="courseProgress" 
            :show-text="false"
            :stroke-width="4"
          />
        </div>
      </div>
      
      <div class="toolbar-right">
        <el-button @click="toggleNotes" :type="showNotes ? 'primary' : ''">
          <el-icon><EditPen /></el-icon>
          笔记
        </el-button>
        <el-button @click="toggleSettings">
          <el-icon><Setting /></el-icon>
          设置
        </el-button>
        <el-button @click="toggleFullscreen">
          <el-icon><FullScreen /></el-icon>
          全屏
        </el-button>
      </div>
    </div>

    <!-- 主要学习区域 -->
    <div class="study-content">
      <!-- 视频播放器 -->
      <div class="video-section" :class="{ 'notes-open': showNotes }">
        <GlobalVideoPlayer
          v-if="currentLesson?.type === 'video'"
          :src="currentLesson.videoUrl"
          :poster="currentLesson.poster"
          @timeupdate="handleVideoProgress"
          @ended="handleVideoEnded"
        />
        
        <!-- 文档内容 -->
        <div v-else-if="currentLesson?.type === 'document'" class="document-content">
          <div class="document-viewer" v-html="currentLesson.content"></div>
        </div>
        
        <!-- 练习题 -->
        <div v-else-if="currentLesson?.type === 'exercise'" class="exercise-content">
          <div class="exercise-header">
            <h3>{{ currentLesson.title }}</h3>
            <div class="exercise-meta">
              <span>难度：{{ currentLesson.difficulty }}</span>
              <span>预计时间：{{ currentLesson.estimatedTime }}</span>
            </div>
          </div>
          
          <div class="exercise-body">
            <div class="exercise-description" v-html="currentLesson.description"></div>
            
            <div class="exercise-editor">
              <el-tabs v-model="activeTab">
                <el-tab-pane label="代码编辑器" name="editor">
                  <div class="code-editor">
                    <textarea 
                      v-model="userCode" 
                      placeholder="在这里编写你的代码..."
                      class="code-textarea"
                    ></textarea>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="运行结果" name="result">
                  <div class="code-result">
                    <pre v-if="codeResult">{{ codeResult }}</pre>
                    <div v-else class="no-result">点击运行按钮查看结果</div>
                  </div>
                </el-tab-pane>
              </el-tabs>
              
              <div class="editor-actions">
                <el-button @click="runCode" type="primary" :loading="running">
                  <el-icon><CaretRight /></el-icon>
                  运行代码
                </el-button>
                <el-button @click="resetCode">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
                <el-button @click="submitExercise" type="success">
                  <el-icon><Check /></el-icon>
                  提交
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 笔记面板 -->
      <div v-if="showNotes" class="notes-panel">
        <div class="notes-header">
          <h3>学习笔记</h3>
          <el-button @click="showNotes = false" circle size="small">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <div class="notes-content">
          <div class="note-editor">
            <el-input
              v-model="newNote"
              type="textarea"
              :rows="4"
              placeholder="记录你的学习心得..."
              @keyup.ctrl.enter="addNote"
            />
            <el-button 
              type="primary" 
              @click="addNote" 
              style="margin-top: 8px; width: 100%;"
            >
              添加笔记
            </el-button>
          </div>
          
          <div class="notes-list">
            <div 
              v-for="note in notes" 
              :key="note.id"
              class="note-item"
            >
              <div class="note-content">{{ note.content }}</div>
              <div class="note-meta">
                <span class="note-time">{{ formatTime(note.timestamp) }}</span>
                <el-button 
                  text 
                  size="small" 
                  @click="deleteNote(note.id)"
                  class="delete-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <div class="study-navigation">
      <div class="nav-left">
        <el-button 
          @click="previousLesson" 
          :disabled="currentLessonIndex === 0"
        >
          <el-icon><ArrowLeft /></el-icon>
          上一课
        </el-button>
      </div>
      
      <div class="nav-center">
        <div class="lesson-list">
          <el-button 
            v-for="(lesson, index) in lessons" 
            :key="lesson.id"
            :type="index === currentLessonIndex ? 'primary' : ''"
            :class="{ completed: lesson.completed }"
            size="small"
            @click="goToLesson(index)"
          >
            {{ index + 1 }}
          </el-button>
        </div>
      </div>
      
      <div class="nav-right">
        <el-button 
          @click="nextLesson" 
          :disabled="currentLessonIndex === lessons.length - 1"
          type="primary"
        >
          下一课
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 设置面板 -->
    <el-drawer
      v-model="showSettings"
      title="播放设置"
      direction="rtl"
      size="300px"
    >
      <div class="settings-content">
        <div class="setting-group">
          <label>播放速度</label>
          <el-select v-model="playbackRate" @change="updatePlaybackRate">
            <el-option label="0.5x" value="0.5" />
            <el-option label="0.75x" value="0.75" />
            <el-option label="1x" value="1" />
            <el-option label="1.25x" value="1.25" />
            <el-option label="1.5x" value="1.5" />
            <el-option label="2x" value="2" />
          </el-select>
        </div>
        
        <div class="setting-group">
          <label>自动播放下一课</label>
          <el-switch v-model="autoPlayNext" />
        </div>
        
        <div class="setting-group">
          <label>显示字幕</label>
          <el-switch v-model="showSubtitles" />
        </div>
        
        <div class="setting-group">
          <label>画质</label>
          <el-select v-model="videoQuality">
            <el-option label="自动" value="auto" />
            <el-option label="1080P" value="1080p" />
            <el-option label="720P" value="720p" />
            <el-option label="480P" value="480p" />
          </el-select>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  ArrowLeft, ArrowRight, EditPen, Setting, FullScreen, Close,
  CaretRight, Refresh, Check
} from '@element-plus/icons-vue'
import GlobalVideoPlayer from '@/components/global/GlobalVideoPlayer.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 响应式数据
const showNotes = ref(false)
const showSettings = ref(false)
const currentLessonIndex = ref(0)
const newNote = ref('')
const notes = ref([])
const activeTab = ref('editor')
const userCode = ref('')
const codeResult = ref('')
const running = ref(false)
const playbackRate = ref('1')
const autoPlayNext = ref(true)
const showSubtitles = ref(false)
const videoQuality = ref('auto')

// 模拟数据
const currentCourse = ref({
  id: 1,
  title: 'Vue3 + TypeScript 实战开发'
})

const lessons = ref([
  {
    id: 1,
    title: 'Vue3介绍和环境搭建',
    type: 'video',
    videoUrl: '/videos/lesson1.mp4',
    poster: '/images/lesson1-poster.jpg',
    duration: '15:30',
    completed: false
  },
  {
    id: 2,
    title: 'Composition API基础',
    type: 'video',
    videoUrl: '/videos/lesson2.mp4',
    poster: '/images/lesson2-poster.jpg',
    duration: '25:45',
    completed: false
  },
  {
    id: 3,
    title: '响应式系统练习',
    type: 'exercise',
    difficulty: '中等',
    estimatedTime: '30分钟',
    description: '<p>请实现一个简单的响应式数据绑定</p>',
    initialCode: 'const { ref, reactive } = Vue;\n\n// 在这里编写你的代码',
    completed: false
  }
])

// 计算属性
const currentLesson = computed(() => {
  return lessons.value[currentLessonIndex.value]
})

const totalLessons = computed(() => {
  return lessons.value.length
})

const courseProgress = computed(() => {
  const completedCount = lessons.value.filter(lesson => lesson.completed).length
  return Math.round((completedCount / totalLessons.value) * 100)
})

// 方法
const goBack = () => {
  router.push('/classroom')
}

const toggleNotes = () => {
  showNotes.value = !showNotes.value
}

const toggleSettings = () => {
  showSettings.value = !showSettings.value
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const previousLesson = () => {
  if (currentLessonIndex.value > 0) {
    currentLessonIndex.value--
  }
}

const nextLesson = () => {
  if (currentLessonIndex.value < lessons.value.length - 1) {
    currentLessonIndex.value++
  }
}

const goToLesson = (index) => {
  currentLessonIndex.value = index
}

const handleVideoProgress = (currentTime) => {
  // 记录学习进度
}

const handleVideoEnded = () => {
  // 标记当前课程为已完成
  lessons.value[currentLessonIndex.value].completed = true
  
  if (autoPlayNext.value && currentLessonIndex.value < lessons.value.length - 1) {
    setTimeout(() => {
      nextLesson()
    }, 2000)
  }
}

const addNote = () => {
  if (newNote.value.trim()) {
    notes.value.unshift({
      id: Date.now(),
      content: newNote.value,
      timestamp: new Date(),
      lessonId: currentLesson.value.id
    })
    newNote.value = ''
    ElMessage.success('笔记添加成功')
  }
}

const deleteNote = (id) => {
  const index = notes.value.findIndex(n => n.id === id)
  if (index > -1) {
    notes.value.splice(index, 1)
    ElMessage.success('笔记删除成功')
  }
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const runCode = async () => {
  running.value = true
  try {
    // 模拟代码执行
    await new Promise(resolve => setTimeout(resolve, 1000))
    codeResult.value = '代码执行成功！\n输出结果：Hello Vue3!'
    activeTab.value = 'result'
  } catch (error) {
    codeResult.value = '代码执行出错：' + error.message
  } finally {
    running.value = false
  }
}

const resetCode = () => {
  userCode.value = currentLesson.value.initialCode || ''
  codeResult.value = ''
}

const submitExercise = () => {
  lessons.value[currentLessonIndex.value].completed = true
  ElMessage.success('练习提交成功！')
}

const updatePlaybackRate = () => {
  // 更新视频播放速度
}

onMounted(() => {
  // 初始化代码编辑器
  if (currentLesson.value?.type === 'exercise') {
    userCode.value = currentLesson.value.initialCode || ''
  }
})

onUnmounted(() => {
  // 清理资源
})
</script>

<style lang="scss" scoped>
.study-room {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;
  color: white;
}

.study-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .course-info {
    display: flex;
    flex-direction: column;
    
    .course-title {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.7);
    }
    
    .lesson-title {
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.toolbar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  
  .progress-info {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 200px;
    
    .el-progress {
      flex: 1;
    }
  }
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.study-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.video-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  
  &.notes-open {
    flex: 0 0 70%;
  }
}

.document-content,
.exercise-content {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: white;
  color: #333;
  overflow-y: auto;
}

.exercise-header {
  margin-bottom: 20px;
  
  h3 {
    margin-bottom: 8px;
  }
  
  .exercise-meta {
    display: flex;
    gap: 20px;
    font-size: 14px;
    color: #666;
  }
}

.exercise-editor {
  .code-textarea {
    width: 100%;
    height: 300px;
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 14px;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 12px;
    resize: vertical;
  }
  
  .code-result {
    height: 300px;
    background: #f5f5f5;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 12px;
    overflow-y: auto;
    
    pre {
      margin: 0;
      font-family: 'Consolas', 'Monaco', monospace;
    }
    
    .no-result {
      color: #999;
      text-align: center;
      padding: 50px 0;
    }
  }
  
  .editor-actions {
    margin-top: 12px;
    display: flex;
    gap: 8px;
  }
}

.notes-panel {
  width: 350px;
  background: rgba(255, 255, 255, 0.95);
  color: #333;
  border-left: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
}

.notes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  
  h3 {
    margin: 0;
    font-size: 16px;
  }
}

.notes-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.note-editor {
  margin-bottom: 20px;
}

.notes-list {
  .note-item {
    padding: 12px;
    border: 1px solid #eee;
    border-radius: 6px;
    margin-bottom: 12px;
    
    .note-content {
      margin-bottom: 8px;
      line-height: 1.5;
    }
    
    .note-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #999;
      
      .delete-btn {
        color: #f56c6c;
      }
    }
  }
}

.study-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.nav-center {
  .lesson-list {
    display: flex;
    gap: 4px;
    
    .el-button {
      width: 32px;
      height: 32px;
      padding: 0;
      
      &.completed {
        background: var(--el-color-success);
        border-color: var(--el-color-success);
      }
    }
  }
}

.settings-content {
  .setting-group {
    margin-bottom: 20px;
    
    label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
    }
    
    .el-select {
      width: 100%;
    }
  }
}

.el-button {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
  
  &.el-button--primary {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }
}

@media (max-width: 768px) {
  .study-content {
    flex-direction: column;
  }
  
  .video-section {
    &.notes-open {
      flex: 1;
    }
  }
  
  .notes-panel {
    width: 100%;
    height: 300px;
  }
  
  .toolbar-center {
    display: none;
  }
}
</style>
